﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using Wicture.DbRESTFul;
using Wicture.DbRESTFul.SQL;
using Wicture.EPC.Service.Etka.QueryInterceptors.Interceptors;

namespace Wicture.EPC.Service.Etka.QueryInterceptors
{
    public static class QueryInterceptorManager
    {
        private static List<IQueryInterceptor> interceotors;
        static QueryInterceptorManager()
        {
            interceotors = new List<IQueryInterceptor>
            {
                new ETKAQueryInterceptor(),
                new PorscheQueryInterceptor()
            };
        }

        public static object Interceptor(DbRESTFulRepository repository, JObject param, [CallerMemberName] string targetName = "")
        {
            var brandCode = param.Value<string>("brandCode");
            var interceptor = interceotors.FirstOrDefault(i => i.BrandCodes.Contains(brandCode));

            try
            {
                return interceptor.GetType().GetMethod(targetName)?.Invoke(interceptor, new object[] { repository, param });
            }
            catch (Exception ex)
            {
                LoggerManager.Logger.LogError(ex, $"Call {targetName} for {brandCode}.");
                throw ex.InnerException;
            }
        }
    }
}


